// 此处实现避免数据竞态，与loader\api-origin-loader.js配合
import { CancelToken } from 'axios'

const record = new WeakMap()

const requestSuccessHandler = function (request) {
  let { refer, method, url, abortDisable } = request
  if (!abortDisable && refer && method === 'get') {
    !record.has(refer) && record.set(refer, {})
    let group = record.get(refer)
    group[url] && group[url]()
    request.cancelToken = new CancelToken(c => {
      group[url] = c
    })
  }
  return request
}

const responseSuccessHandler = function (response) {
  let { refer, method, url, abortDisable } = response.config
  if (!abortDisable && refer && method === 'get') {
    let group = record.get(refer)
    group[url] && (group[url] = null)
  }
  return Promise.resolve(response)
}

export default {
  requestSuccessHandler,
  responseSuccessHandler
}
